%%%-------------------------------------------------------------------
%%% @author wukai
%%% @copyright (C) 2017, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 08. 十一月 2017 11:48
%%%-------------------------------------------------------------------
-module(frame_unsub).
-author("wukai").
-include("../include/mqtt_protocol.hrl").
%% API
-export([do_command/3]).

do_command(Ref,State,Frame)when Frame#mqtt_frame.frame_flag == 2->
  <<MsgId:16, Topics/binary>> = Frame#mqtt_frame.left_bytes,
  lager:log(info,self(),"ubsubscribe msgid ~p",[MsgId]),
  case topics_binary(Topics) of
    {error,Info}->
      lager:log(info, self(), "~p", [Info]),
      mqtt_process:exit_self();
    {ok,Subscribes}->
      un_sub(Subscribes,State#state.client),
      ack(Ref,State,MsgId)
  end,
  State;

%%校验固定报头标志位 如果不等于2 则关闭网络连接 v4
do_command(_,_,_)->
  lager:log(info,self(),"ubsubscribe frame flag error"),
  mqtt_process:exit_self().

parse_topics(TopicsBin, List) when byte_size(TopicsBin) > 0 ->
  try
    <<Tlen:16, Topic:Tlen/binary, Topics/binary>> = TopicsBin,
    lager:log(info, self(), "unsubscribe topic name ~p", [Topic]),
    parse_topics(Topics, List ++ [Topic])
  catch _:_ -> {error,"match binary errror"}
  end;
parse_topics(TopicsBin, List) when byte_size(TopicsBin) == 0 ->
  lager:log(info,self(),"unsubscribe topics ~p",[List]),
  {ok,List}.
topics_binary(Bin) when byte_size(Bin) == 0 ->
  {error, "no topics unsubscribe"};
topics_binary(Bin) -> parse_topics(Bin, []).

ack(_,State,Mid)->
  mqtt_process:send_binary(State,<<?FRAME_UNSUB_ACK:4,0:4,2:?UBYTE,Mid:16>>).

un_sub(TL,Client) when is_list(TL)->
  subscribe_server:send_unsub(TL,Client,self()).

